package yorkcc;

import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Serial {

    private static CommPortIdentifier portId;
    private static SerialPort serialPort;
    private static OutputStream outputStream;
    public static InputStream inputStream;
    private static String strBuffer = "";
    private static String strResp = "";
    public static Boolean isConnected = false;

    public static void Connect() {
        if (!isConnected) {
            try {
                portId = CommPortIdentifier.getPortIdentifier(Vars.prop.getProperty("PortName"));
            } catch (NoSuchPortException ex) {
                Logger.getLogger(Serial.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                serialPort = (SerialPort) portId.open("SimpleWrite", 2000);
            } catch (PortInUseException ex) {
                Logger.getLogger(Serial.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            } catch (UnsupportedCommOperationException ex) {
                Logger.getLogger(Serial.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                serialPort.enableReceiveTimeout(1000);
            } catch (UnsupportedCommOperationException ex) {
                Logger.getLogger(Serial.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                outputStream = serialPort.getOutputStream();
                inputStream = serialPort.getInputStream();
            } catch (IOException ex) {
                Logger.getLogger(Serial.class.getName()).log(Level.SEVERE, null, ex);
            }
            (new Thread(new SerialReader())).start();
            isConnected = true;
        }
    }

    private static void Disconnect() {
        if (isConnected) {
            isConnected = false;
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
            }
            try {
                inputStream.close();
                outputStream.close();
            } catch (IOException ex) {
                Logger.getLogger(Serial.class.getName()).log(Level.SEVERE, null, ex);
            }
            serialPort.close();
        }
    }

    public static class SerialReader implements Runnable {

        public void run() {
            byte[] buffer = new byte[1024];
            int len = -1;
            String s = "";
            try {
                while ((len = inputStream.read(buffer)) > -1 && isConnected) {
                    if (len > 0) {
                        s = new String(buffer, 0, len);
                        s = s.replace("\n", "|");
                        s = s.replace("\r", "|");
                        strResp += s;
                        s = s.replace("|", "\n");
                        strBuffer += s;
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(Serial.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static String getStringBuffer() {
        String sb = strBuffer;
        strBuffer = "";
        return sb;
    }

    public static String[] getResp(Integer strNum) {
        String[] strs = {""};
        int counter = 0;
        if (strNum > 0) {
            while (strs.length < strNum && counter < 50) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                }
                strs = strResp.split("\\|");
                counter++;
            }
        }
        if (strNum == 0) {
            while (!strs[strs.length - 1].endsWith(">") && counter < 50) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                }
                strs = strResp.split("\\|");
                counter++;
            }
        }
        if (strNum < 0) {
            while (!strs[strs.length - 1].endsWith(">") && counter < (0 - strNum)) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
                strs = strResp.split("\\|");
                counter++;
            }
        }
        return strs;
    }

    public static void sendCmd(String cmd) {
        strResp = "";
        byte[] command_b = null;
        try {
            command_b = (cmd + "\r").getBytes("ASCII");
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            outputStream.write(command_b);
            outputStream.flush();
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
